package cn.doitedu.javase.thread_pool;

import java.util.concurrent.*;

public class _02_各种juc中的线程池api示例 {
    public static void main(String[] args) {

        // 固定数量的线程池
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        //fixedThreadPool.submit(new MyTask(1));
        //fixedThreadPool.submit(new MyTask(2));

        // 单线程的线程池（严格来说它不是一个池，而只是一个线程执行器）
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        //singleThreadExecutor.submit(new MyTask(3));


        // 内部会初始化默认数量0个线程
        // 池会根据需要，动态添加新的线程
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        //cachedThreadPool.submit(new MyTask(4));
        //cachedThreadPool.submit(new MyTask(5));


        // 调度线程池
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);

        // 固定周期调度：每2秒重复执行一次提交的任务
        // 当然，如果任务的执行时长超过了周期，则等任务执行完成的瞬间才会启动下一次执行
        scheduledThreadPool.scheduleAtFixedRate(new MyTaskRunnable(),5,2, TimeUnit.SECONDS);


        // 固定延迟调度：每次启动都是上一次执行完之后延迟一个固定的时长
        scheduledThreadPool.scheduleWithFixedDelay(new MyTaskRunnable(),5,2,TimeUnit.SECONDS);
        scheduledThreadPool.schedule(new MyTaskRunnable(),2,TimeUnit.SECONDS);
        scheduledThreadPool.schedule(new MyTask(1),2,TimeUnit.SECONDS);



    }

}


class MyTaskRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println(System.currentTimeMillis() + ": 执行了");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}


class MyTask implements Callable<String>{

    int taskId;
    public MyTask(int taskId){
        this.taskId = taskId;
    }


    @Override
    public String call() throws Exception {

        System.out.println(taskId+ " : 开始工作");

        Thread.sleep(2000);

        return taskId+" complete";
    }
}